<template>
  <el-card class="box-card">
    <el-breadcrumb separator-class="el-icon-arrow-right" style="width: 300px">
      <el-breadcrumb-item style="font-size: 16px">首页</el-breadcrumb-item>
      <el-breadcrumb-item style="font-size: 16px"
        >高考资讯管理</el-breadcrumb-item
      >
      <el-breadcrumb-item style="font-size: 16px">高考资讯</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="addNews">
      <!-- 对话框组件  :visible.sync(设置是否显示对话框) width(设置对话框的宽度)
:before-close(在对话框关闭前触发的事件) -->
      <el-dialog
        title="添加新闻"
        :visible.sync="addDialogVisible"
        width="40%"
        @close="addDialogClosed()"
      >
        <!-- 对话框主体区域 -->
        <el-form
          :model="addForm"
          :rules="newsRules"
          ref="addFormRef"
          label-width="80px"
          style="padding: 10px 20px"
        >
          <el-form-item label="标题" prop="title" style="height: 50px">
            <el-input v-model="addForm.title" style="width: 50%"></el-input>
          </el-form-item>
          <el-form-item label="文章链接" prop="link" style="height: 50px">
            <el-input v-model="addForm.link" style="width: 50%"></el-input>
          </el-form-item>
          <el-form-item label="文章来源" prop="source" style="height: 50px">
            <el-input v-model="addForm.source" style="width: 50%"></el-input>
          </el-form-item>
          <el-form-item label="分类" prop="type" style="height: 50px">
            <el-input v-model="addForm.type" style="width: 50%"></el-input>
          </el-form-item>
        </el-form>
        <!-- 对话框底部区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addCancel">取 消</el-button>
          <el-button type="primary" @click="addNews">确 定</el-button>
        </span>
      </el-dialog>
      <el-button
        v-if="showAdd"
        type="primary"
        @click="addDialogVisible = true"
        style="float: right; margin-top: -25px; margin-right: 75px"
        >添加新闻</el-button
      >
    </div>
    <el-table
      :data="userData"
      border
      style="
        width: 1041px;
        position: relative;
        text-align: center;
        margin-left: 10px;
        top: 10px;
      "
      :header-cell-style="headClass"
    >
      <el-table-column label="序号" width="80" type="index" align="center">
      </el-table-column>
      <el-table-column label="标题" width="320" prop="name" align="center">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.title }}</span>
        </template>
      </el-table-column>
      <el-table-column label="文章链接" width="300" prop="hot" align="center">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.link }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="文章来源"
        width="120"
        prop="iscoment"
        align="center"
      >
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.source }}</span>
        </template>
      </el-table-column>
      <el-table-column label="分类" width="120" prop="category" align="center">
        <template slot-scope="scope">
          <span style="margin-left: 10px" v-if="scope.row.type === 1"
            >高考推荐</span
          >
          <span style="margin-left: 10px" v-if="scope.row.type === 2"
            >高考信息</span
          >
          <span style="margin-left: 10px" v-if="scope.row.type === 3"
            >专业解读</span
          >
          <span style="margin-left: 10px" v-if="scope.row.type === 4"
            >志愿填报</span
          >
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100" align="center">
        <template slot-scope="scope">
          <el-button
            v-if="showRemove"
            size="mini"
            type="danger"
            icon="el-icon-delete"
            @click="removeNewsById(scope.row.title)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      class="pagination"
      @current-change="handleCurrentChange"
      :current-page="queryInfo.pagenum"
      :page-size="queryInfo.pagesize"
      layout="total, prev, pager, next"
      :total="queryInfo.count"
      background
    >
      <!--
        @current-change(页码发生改变时触发)
        :current-page(设置当前页码)
        :page-size(设置每页的数据条数)
        :total(设置总页数)
     -->
    </el-pagination>
  </el-card>
</template>

<script>
import qs from "qs";
import throttling from "@/public/throttling.js";
export default {
  data() {
    var validateLink = (rule, value, callback) => {
      let reg =
        /([hH][tT]{2}[pP]:\/\/|[hH][tT]{2}[pP][sS]:\/\/|[wW]{3}.|[wW][aA][pP].|[fF][tT][pP].|[fF][iI][lL][eE].)[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]/;
      if (!value) {
        callback(new Error("请填写文章链接！"));
      } else {
        if (!reg.test(value)) {
          callback(new Error("请正确填写文章链接!"));
        } else {
          callback();
        }
      }
    };
    return {
      // 按钮显示隐藏
      showAdd: true,
      showRemove: true,
      // 添加
      addDialogVisible: false,
      addForm: {
        title: "",
        link: "",
        source: "",
        coment: "",
        type: "",
      },
      newsRules: {
        title: [{ required: true, message: "请输入文章标题", trigger: "blur" }],
        link: [{ validator: validateLink, tigger: "blur" }],
        source: [
          { required: true, message: "请输入文章来源", trigger: "blur" },
        ],
        type: [{ required: true, message: "请输入文章类型", trigger: "blur" }],
      },
      //初始分页条件
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 5,
        count: 0,
      },
      // 保存请求回来的用户列表数据
      userData: [
        {
          title: "",
          link: "",
          iscoment: 0,
          category: "",
        },
      ],
      dialogTableVisible: false,
      dialogFormVisible: false,
      form: {
        name: "",
        region: "",
        date1: "",
        date2: "",
        delivery: false,
        type: [],
        resource: "",
        desc: "",
      },
      formLabelWidth: "120px",
    };
  },
  methods: {
    // 表格表头
    headClass() {
      //表头居中显示
      return "color:rgba(255,101,0);font-weight:bold;font-size:16px";
    },
    getUserList_Token() {
      const token = window.sessionStorage.getItem("tokenvalue");
      this.$axios.defaults.headers.common["satoken"] = token;
      this.$axios
        .get("/back/news", {
          params: {
            page: this.queryInfo.pagenum,
            size: this.queryInfo.pagesize,
          },
        })
        .then((res) => {
          console.log(res);
          if (res.data.status === 666) {
            this.$message.error("请先登录");
            this.$router.replace("/login");
          } else if (res) {
            this.$message.success("获取新闻列表成功！");
            this.userData = res.data.data;
            this.queryInfo.count = res.data.code;
          }
        });
    },
    // 添加
    addDialogClosed() {
      // 对话框关闭之后，重置表单
      this.$refs.addFormRef.resetFields();
    },
    addCancel() {
      this.addDialogVisible = false;
      this.$message("取消修改");
    },
    showAddDialog() {
      //显示弹出窗
      this.editDialogVisible = true;
      // });
    },
    addNews: throttling(function () {
      this.$refs.addFormRef.validate((valid) => {
        if (!valid) this.$message.error("请输入完整的高考资讯信息");
        this.$axios
          .post(
            "/back/news",
            qs.stringify({
              title: this.addForm.title,
              link: this.addForm.link,
              source: this.addForm.source,
              type: this.addForm.type,
            })
          )
          .then((res) => {
            console.log(res);
            this.$message.success("添加新闻成功！");
            this.addDialogVisible = false;
            this.getUserList_Token();
          });
      });
    }, 1000),
    addDialogClosed() {
      // 对话框关闭之后，重置表单
      this.$refs.addFormRef.resetFields();
    },
    // 删除
    removeNewsById(title) {
      //弹出确定取消框，是否删除用户
      this.$confirm("请问是否要永久删除该资讯", "删除提示", {
        distinguishCancelAndClose: true,
        confirmButtonText: "确认删除",
        cancelButtonText: "取消",
      })
        .then(() => {
          //发送请求根据id完成删除操作
          this.$axios
            .delete("/back/news", {
              params: {
                title: title,
              },
            })
            .then((res) => {
              console.log(res);
              //修改成功的提示
              this.$message.success("删除高考资讯成功");
              //重新请求最新的数据
              this.getUserList_Token();
            });
        })
        .catch((action) => {
          this.$message({
            type: "info",
            message: action === "cancel" ? "取消删除" : "放弃删除",
          });
        });
    },
    handleSelect(key, keyPath) {
      console.log(key, keyPath);
    },
    handleCurrentChange: throttling(function (page) {
      this.queryInfo.pagenum = page;
      //   this.getLists();
      console.log("跳转了");
      // 重新按照pagenum发送请求 请求最新的数据
      this.getUserList_Token();
    }, 1000),
  },
  created() {
    this.$axios.get("/back/news/deleteButton").then((res) => {
      if (res.data.code === 500) {
        this.showRemove = false;
      }
    });
    this.$axios.get("/back/news/addButton").then((res) => {
      if (res.data.code === 500) {
        this.showAdd = false;
      }
    });
    this.getUserList_Token();
  },
};
</script>

<style scoped>
.box-card {
  position: relative;
  margin: 22px auto;
  min-height: 550px;
}
.text {
  font-size: 14px;
}

.item {
  padding: 18px 0;
}

.search {
  margin-top: 20px;
  margin-left: 40px;
}

.el-table {
  margin-top: 20px;
}

.el-dialog .el-dialog__body {
  padding: 10px 20px;
}

.el-form-item {
  margin-bottom: 10px;
}

.pagination {
  position: absolute;
  bottom: 20px;
  width: 412px;
  margin: 5px auto;
  left: 50%;
  margin-left: -206px;
}
</style>